package com.bupt.service;

import com.bupt.bean.AlarmStrategy;
import com.bupt.bean.Device;
import com.bupt.config.AlarmStrategyResult;
import com.bupt.config.CommonCode;
import com.bupt.config.Result;
import com.bupt.dao.AlarmStrategyRepository;
import com.bupt.dao.DeviceRepository;
import com.bupt.vo.SysConst;
import com.bupt.vo.AttributeValueCheckTypeVo;
import com.bupt.vo.DeviceTypeAttributeCheckVo;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.sql.Timestamp;
import java.util.List;

@Transactional
@Service
public class AlarmStrategyService {

    @Autowired
    private DeviceRepository deviceRepository;

    @Autowired
    private AlarmStrategyRepository alarmStrategyRepository;

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private PrimaryKeyService primaryKeyService;


    //删除报警策略配置
    public Result deleteById(Integer alarmStrategyId) {
        Result result = new Result();
        AlarmStrategy alarmStrategy = alarmStrategyRepository.findByAlarmStrategyId(alarmStrategyId);
        if(alarmStrategy!=null){

            alarmStrategyRepository.deleteByAlarmStrategyId(alarmStrategyId);
            result.setResult("删除成功");
            return result;
        }
        result.setResult("删除失败");
        return result;
    }

    //报警策略配置级别
    public List<SysConst> strategyLevel() {
        String sql = "SELECT const_value,const_desc FROM sys_const_t WHERE const_group_name='STRATEGY_TYPE'";
                Query query = entityManager.createNativeQuery(sql);
                List<SysConst> sysConstList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return sysConstList;
    }

    //报警策略配置状态
    public List<SysConst> status() {
        String sql = "SELECT const_value,const_desc FROM sys_const_t WHERE const_group_name='STRATEGY_STATUS'";
        Query query = entityManager.createNativeQuery(sql);
        List<SysConst> sysConstList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return sysConstList;

    }

    //监控参数
    public List<DeviceTypeAttributeCheckVo> attributeCheck(Integer deviceTypeId) {
        String sql = "SELECT device_type_attribute_check_id,attribute_name_cn,attribute_value_type_id FROM device_type_attribute_check_t WHERE device_type_id="+deviceTypeId;
        Query query = entityManager.createNativeQuery(sql);
        List<DeviceTypeAttributeCheckVo> deviceTypeAttributeCheckVoList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return deviceTypeAttributeCheckVoList;
    }

    //检测类型
    public List<AttributeValueCheckTypeVo> checkType(Integer attributeValueTypeId) {
        String sql = "SELECT attribute_value_check_type_id,attribute_value_check_type_name FROM attribute_value_check_type_t WHERE attribute_value_type_id="+attributeValueTypeId;
        Query query = entityManager.createNativeQuery(sql);
        List<AttributeValueCheckTypeVo> attributeValueCheckTypeVoList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return attributeValueCheckTypeVoList;
    }

    //报警策略配置添加页面
    public AlarmStrategyResult add(Integer deviceId,Integer strategyLevel, Integer deviceChannelId, Integer channelSectionId, Integer deviceTypeAttributeCheckId, Integer attributeValueCheckTypeId, String threshold, Integer status) {

        //校验设备是否存在
        Device byDeviceId = deviceRepository.findByDeviceId(deviceId);
        if(byDeviceId==null){
            return new AlarmStrategyResult(CommonCode.NOTDEVICEFAIL,new AlarmStrategy());
        }else{
            AlarmStrategy alarmStrategy = new AlarmStrategy();
            Integer alarm_strategy_id = primaryKeyService.getPrimaryKey("ALARM_STRATEGY_ID");
            alarmStrategy.setAlarmStrategyId(alarm_strategy_id);
            alarmStrategy.setDeviceId(deviceId);
            alarmStrategy.setDeviceChannelId(deviceChannelId);
            alarmStrategy.setChannelSectionId(channelSectionId);

            String sql = "SELECT attribute_name_en,attribute_name_cn,attribute_value_type_id FROM device_type_attribute_check_t WHERE device_type_attribute_check_id="+deviceTypeAttributeCheckId;
            Query nativeQuery = entityManager.createNativeQuery(sql);
            List resultList = nativeQuery.getResultList();
            Object[] objects = (Object[]) resultList.get(0);
            String attribute_name_en = objects[0].toString();
            String attribute_name_cn = objects[1].toString();
            String attribute_value_type_id = objects[2].toString();

            alarmStrategy.setAttributeNameEn(attribute_name_en);
            alarmStrategy.setAttributeNameCn(attribute_name_cn);
            alarmStrategy.setAttributeValueTypeId(Integer.valueOf(attribute_value_type_id));

            alarmStrategy.setAttributeValueCheckTypeId(attributeValueCheckTypeId);
            alarmStrategy.setThreshold(threshold);
            alarmStrategy.setStrategyLevel(strategyLevel);
            alarmStrategy.setCreateTime(new Timestamp(System.currentTimeMillis()));
            alarmStrategy.setStatus(status);
            alarmStrategy.setDeviceTypeAttributeCheckId(deviceTypeAttributeCheckId);


            alarmStrategyRepository.save(alarmStrategy);

            AlarmStrategyResult alarmStrategyResult = new AlarmStrategyResult(CommonCode.SUCCESS, alarmStrategy);
            return alarmStrategyResult;
        }
    }

    //修改阀值和状态
    public AlarmStrategyResult editAlarmStrategyById(Integer alarmStrategyId, AlarmStrategy alarmStrategy) {
        AlarmStrategy beforAlarmStrategy = alarmStrategyRepository.findByAlarmStrategyId(alarmStrategyId);
        if (beforAlarmStrategy != null) {
            beforAlarmStrategy.setThreshold(alarmStrategy.getThreshold());
            beforAlarmStrategy.setStatus(alarmStrategy.getStatus());
            beforAlarmStrategy.setAttributeValueCheckTypeId(alarmStrategy.getAttributeValueCheckTypeId());

            String sql = "SELECT attribute_name_en,attribute_name_cn,attribute_value_type_id FROM device_type_attribute_check_t WHERE device_type_attribute_check_id="+alarmStrategy.getDeviceTypeAttributeCheckId();
            Query nativeQuery = entityManager.createNativeQuery(sql);
            List resultList = nativeQuery.getResultList();
            Object[] objects = (Object[]) resultList.get(0);
            String attribute_name_en = objects[0].toString();
            String attribute_name_cn = objects[1].toString();
            String attribute_value_type_id = objects[2].toString();

            beforAlarmStrategy.setAttributeNameEn(attribute_name_en);
            beforAlarmStrategy.setAttributeNameCn(attribute_name_cn);
            beforAlarmStrategy.setAttributeValueTypeId(Integer.valueOf(attribute_value_type_id));
            //beforAlarmStrategy.setAttributeValueTypeId(alarmStrategy.getDeviceTypeAttributeCheckId());
        }

        AlarmStrategy save = alarmStrategyRepository.save(beforAlarmStrategy);
        if (save != null) {
            AlarmStrategyResult alarmStrategyResult = new AlarmStrategyResult(CommonCode.SUCCESS, beforAlarmStrategy);
            return alarmStrategyResult;
        }
        return new AlarmStrategyResult(CommonCode.FAILs, null);
    }
}
